package com.itheima.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.pojo.Orders;
import com.itheima.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.PublicKey;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @GetMapping("/userPage")
    public R<Page> page(Integer page,Integer pageSize){
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        ordersService.page(ordersPage, queryWrapper);
        return R.success(ordersPage);

    }


    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        ordersService.submit(orders);
        return R.success("下单成功");
    }
    @GetMapping("/page")
    public R<Page> pageR(int page,int pageSize,String number,String beginTime,String endTime){
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(number!=null,Orders::getId,number);
        queryWrapper.ge(beginTime!=null,Orders::getOrderTime,beginTime);
        queryWrapper.le(endTime!=null,Orders::getOrderTime,endTime);
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //执行查询
        ordersService.page(ordersPage,queryWrapper);
        List<Orders> records = ordersPage.getRecords();
        records.stream().map((item)->{
            item.setUserName("用户"+item.getUserId());
            return item;
                }).collect(Collectors.toList());
        return R.success(ordersPage);
    }

    @PutMapping
    public R<String> update(@RequestBody Orders orders){
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Orders::getId,orders.getId());
        updateWrapper.set(Orders::getStatus,orders.getStatus());
        ordersService.update(updateWrapper);
        return R.success("派送成功");
    }

    @GetMapping("/export")
    public void easyExcel(String beginTime, String endTime, HttpServletResponse response) throws Exception {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");


        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName= URLEncoder.encode("测试","UTF-8").replaceAll("\\+","%20");

         fileName = UUID.randomUUID().toString();
        response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName+".xlsx");

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(StringUtils.isNotEmpty(beginTime)&&StringUtils.isNotEmpty(endTime),//动态sql
                Orders::getOrderTime,
                beginTime,
                endTime);
        List<Orders> list = ordersService.list(wrapper);
        EasyExcel.write(response.getOutputStream(),Orders.class).sheet("模板").doWrite(list);
    }


}
